package club.jdiy.core.base;

import java.util.HashMap;
import java.util.Map;

/**
 * JPA query 动态查询条件构建对象.
 *
 * 由实现了{@link club.jdiy.core.base.domain.JpaFilterable} 的实体类中
 * {@link club.jdiy.core.base.domain.JpaFilterable#createFilter(WhereBuilder)}方法入参使用。用于构造JPA动态查询条件
 *
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20210708
 */
public final class WhereBuilder {
    private final StringBuilder wheres = new StringBuilder("1=1");
    private final Map<String, Object> paramsMap = new HashMap<>();
    private int idx = 0;

    public WhereBuilder append(String condition, Object... params) {
        if (params != null && params.length > 0) {
            String p;
            for (int i = 0; i < params.length; i++) {
                condition = condition.replaceAll("\\?" + (1 + i), ":" + (p = "p" + idx++));
                paramsMap.put(p, params[i]);
            }
        }
        wheres.append(" ").append(condition);
        return this;
    }


    final Map<String, Object> getParams() {
        return paramsMap;
    }

    @Override
    public String toString() {
        return wheres.toString();
    }
}
